package com.example.myapplication

import android.annotation.SuppressLint
import android.content.*
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.*
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.webkit.WebView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.myapplication.databinding.ActivityMainBinding
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import com.sunmi.scanner.IScanInterface
import kotlinx.coroutines.*
import org.json.JSONObject
import java.util.*


class MainActivity : AppCompatActivity() {
    companion object {
        const val TAG = "Scan-Test"
        const val ACTION_DATA_CODE_RECEIVED = "com.sunmi.scanner.ACTION_DATA_CODE_RECEIVED"
        const val DATA = "data"
        const val SOURCE = "source_byte"
        const val NONE = 100

    }

    private lateinit var mBinding: ActivityMainBinding
    private var mHandler = Handler(Looper.getMainLooper())
    private var scanInterface: IScanInterface? = null
    private  var mAgentWeb:  AgentWeb?=null
    private var timerTask: TimerTask?=null
    private val br = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                ACTION_DATA_CODE_RECEIVED -> {
                    var code = intent.getStringExtra(DATA)
                    code=code.toString()
                    val source = intent.getByteArrayExtra(SOURCE)
                    Log.d("CCCC", "onReceive: $code")
                    timerTask!!.cancel()
//                    val json2 = "{\"status_code\":200,\"code\":${code.toString()}}"
//                    Log.e("json2",json2);

                    val ja = JSONObject();
                    ja.put("status_code",200);
                    ja.put("code",code);
                    Log.e("json2",ja.toString())

                    mBinding.webview.loadUrl("javascript:callScanBack('"+ja.toString()+"')");
//                    mBinding.webview.loadUrl("javascript:test()");
//                    Toast.makeText(context,"广播接收扫码内容："+code.toString(),Toast.LENGTH_LONG).show()
                }

                else -> {
                }
            }
        }
    }

    private val conn: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            scanInterface = IScanInterface.Stub.asInterface(service)
            Log.i(TAG, "Scanner Service Connected!")
            println("Test chen onServiceConnected")

        }

        @SuppressLint("CheckResult")
        override fun onServiceDisconnected(name: ComponentName) {
            Log.e(TAG, "Scanner Service Disconnected!")
            scanInterface = null
        }
    }

    private fun bindScannerService() {
        println("Test chen bindScannerService 0000")
        if (scanInterface == null) {
            println("Test chen bindScannerService 1111")
            val intent = Intent()
            intent.setPackage("com.sunmi.scanner")
            intent.action = "com.sunmi.scanner.IScanInterface"
            startService(intent)
            bindService(intent, conn, BIND_AUTO_CREATE)
        }
    }

    private fun unbindScannerService() {
        mHandler.removeCallbacksAndMessages(null)
        try {
            if (scanInterface != null) {
                unbindService(conn)
                scanInterface = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun doScanInterface(runnable: Runnable) {
        if (scanInterface == null) {
            bindScannerService()
            mHandler.postDelayed(object : Runnable {
                override fun run() {
                    if (scanInterface != null) {
                        runnable.run()
                    } else {
                        mHandler.postDelayed(this, 200)
                    }
                }
            }, 200)
        } else {
            runnable.run()
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bindScannerService()
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        val  webSettings = mBinding.webview.settings
        webSettings.javaScriptEnabled = true
        webSettings.domStorageEnabled = true
        webSettings.defaultTextEncodingName = "utf-8"
//        mBinding.webview.webChromeClient = mWebChromeClient
        mBinding.webview.webViewClient = mWebViewClient


        webSettings.setJavaScriptEnabled(true);
        // init webview settings
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        webSettings.setJavaScriptEnabled(true);

        webSettings.setDomStorageEnabled(true);
        // 设置在WebView内部是否允许访问文件，默认允许访问。
        webSettings.setAllowFileAccess(true);
        // 设置在WebView内部是否允许访问ContentProvider，默认允许访问。
        webSettings.setAllowContentAccess(true);
        // 设置在WebView内部是否允许通过file url加载的 Js代码读取其他的本地文件
        // Android 4.1前默认允许，4.1后默认禁止
        webSettings.setAllowFileAccessFromFileURLs(true);
        // 设置WebView内部是否允许通过 file url 加载的 Javascript 可以访问其他的源(包括http、https等源)
        // Android 4.1前默认允许，4.1后默认禁止
        webSettings.setAllowUniversalAccessFromFileURLs(true);

        mBinding.webview.addJavascriptInterface(AndroidInterface(  AndroidInterface.AndroidInterfaceCallBack {
            GlobalScope.launch(Dispatchers.IO) {
                time()
                scanInterface?.scan()
            }
        }),"android")
//        mBinding.webview.loadUrl("https://www.jd.com")
//        mBinding.webview.loadUrl("file:///android_asset/web/index.html")

        mBinding.webview.loadUrl("http://172.22.160.50:88")
//        val ja = JSONObject();
//        ja.put("status_code",200);
//        ja.put("code","10000779202401250187");
//        Log.e("json2",ja.toString())


    }

    fun getPackageInfo(context: Context, pkg: String?): PackageInfo {
        var packageInfo: PackageInfo?
        try {
            packageInfo = context.packageManager.getPackageInfo(pkg!!, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            packageInfo = null
            e.printStackTrace()
        }
        return packageInfo!!
    }
    private var firstBackTime:Long = 0;
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            if(mBinding.webview.canGoBack()){
                mBinding.webview.goBack();
            }else{
                if (System.currentTimeMillis() - firstBackTime > 2000) {
                    Toast.makeText(this, "再次点击退出程序", Toast.LENGTH_SHORT).show();
                    firstBackTime = System.currentTimeMillis();
                    //表示如果两次点击间隔时间超过两秒则退出无效
                    return false;
                } else {
                    finish();
                    System.exit(keyCode);
                }
            }

            return true;
        }
        return super.onKeyDown(keyCode, event)
    }

    fun hasScanner(ctx: Context?): Boolean {
        val info: PackageInfo? = ctx?.let { getPackageInfo(it, "com.sunmi.scanner") }
        if (info != null) {
            return compareVer(info.versionName, "4.4.4", true, 3)
        }
        return false
    }

    fun time(){
        var timer = Timer()
        timerTask = object : TimerTask() {
            override fun run(){
                runOnUiThread {
                    val json2 = "{\"status_code\":204,\"code\":\"\"}"
                    mBinding.webview.loadUrl("javascript:callScanBack('"+json2+"')");
                    Log.i("json2", json2)
                }
            }
        }
// 添加任务，设定开始计时器时间，第2个参数为时间单位毫秒，如果是0，立即执行
        timer.schedule(timerTask, 3000)

    }

    fun compareVer(nVer: String, oVer: String, isEq: Boolean, bit: Int): Boolean {
        if (nVer.isEmpty() || oVer.isEmpty()) return false
        val nArr = nVer.split("[.]".toRegex()).dropLastWhile { it.isEmpty() }
            .toTypedArray()
        val oArr = oVer.split("[.]".toRegex()).dropLastWhile { it.isEmpty() }
            .toTypedArray()
        if (nArr.size < bit || oArr.size < bit) return false
        var vup = false
        for (i in 0 until bit) {
            val n = nArr[i].toInt()
            val o = oArr[i].toInt()
            if (n >= o) {
                if (n > o) {
                    vup = true
                    break
                } else if (isEq && i == bit - 1) {
                    vup = true
                    break
                }
            } else {
                break
            }
        }
        return vup
    }

    private val mWebViewClient: WebViewClient = object : WebViewClient() {
        override fun onPageFinished(p0: WebView?, p1: String?) {
            super.onPageFinished(p0, p1)
//            mBinding.webview.loadUrl("javascript:test()");
        }
    }
    private val mWebChromeClient: WebChromeClient = object : WebChromeClient() {

    }



    override fun onResume() {
        super.onResume()
        registerReceiver(br, IntentFilter(ACTION_DATA_CODE_RECEIVED))
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }


    override fun onPause() {
        super.onPause()
        unregisterReceiver(br)
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        GlobalScope.launch(Dispatchers.IO) {
            scanInterface?.scan()
            scanInterface?.stop()
            scanInterface?.scannerModel
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindScannerService()
    }

    fun onScan() {
        GlobalScope.launch(Dispatchers.IO) {
            scanInterface?.scan()
        }
        /*doScanInterface(object : Runnable {
            override fun run() {
                if (scanInterface != null) {
                    scanInterface?.scan()
                } else {
                    mHandler.postDelayed(this, 200)
                }
            }
        })*/
    }

    fun onStop(view: View) {
        GlobalScope.launch(Dispatchers.IO) {
            scanInterface?.stop()
        }
        /*doScanInterface(object : Runnable {
            override fun run() {
                if (scanInterface != null) {
                    scanInterface?.stop()
                } else {
                    mHandler.postDelayed(this, 200)
                }
            }
        })*/
    }
}